import fetch from 'dva/fetch';
import checkStatus from './checkStatus';
import store from "../index";
import ip from './../ip';
import interceptor from "./interceptor";

export default function requsetFecth(url, options) {
  const defaultOptions = {
    credentials: 'include',
  };
  const newOptions = { ...defaultOptions, ...options };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        ...newOptions.headers,
      };
      newOptions.body = JSON.stringify(newOptions.body);
    } else {
      // newOptions.body is FormData
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
        ...newOptions.headers,
      };
    }
  }
  let requestUrl =ip + url;
  return fetch(requestUrl, newOptions)
    .then(checkStatus)
    .then(response => {
      if (newOptions.method === 'DELETE' || response.status === 204) {
        return response.text();
      }
      return response.json().then((data)=>{
       return interceptor(data);
      });
    })
    .catch(e => {
      const status = e.name;
      if (status === 401) {
        return;
      }
      if (status === 403) {
        //  dispatch(routerRedux.push('/exception/403'));
        return;
      }
      if (status <= 504 && status >= 500) {
        //  dispatch(routerRedux.push('/exception/500'));
        return;
      }
      if (status >= 404 && status < 422) {
        //  dispatch(routerRedux.push('/exception/404'));
      }
    });
}
